package com.sgb.kjwl.view.ui.activity.house;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;

import com.sgb.kjwl.databinding.ActivityLeaseCategoryListBinding;
import com.sgb.kjwl.di.machine.DaggerMachineComponent;
import com.sgb.kjwl.di.machine.MachineModule;
import com.sgb.kjwl.model.entity.lease.LeaseListEntity;
import com.sgb.kjwl.model.entity.request.CarFilterJson;
import com.sgb.kjwl.model.entity.request.FactoryFilterJson;
import com.sgb.kjwl.model.entity.request.FarmFilterJson;
import com.sgb.kjwl.model.entity.request.HouseFilterJson;
import com.sgb.kjwl.model.entity.request.LandFilterJson;
import com.sgb.kjwl.model.entity.request.LeaseMachineFilterJson;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.kjwl.view.ui.adapter.machine.LeaseListAdapter;
import com.sgb.kjwl.view.widget.DictWindow5;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.viewmodel.house.LeaseCategoryListActivityModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerViewItemDecoration2;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 二级自营筛选界面
 */
public class LeaseCategoryListActivity extends AppActivity {
    @Inject
    LeaseCategoryListActivityModel viewModel;
    private ActivityLeaseCategoryListBinding binding;

    private List<DictEntity3> CategoryList;//二级类目数据
    private List<DictEntity3> sortDictEntityList;//排序数据
    private DictWindow5 sortWindow;
    private ThreeLevelAreaWindow mAddressPop;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> areaEntityList;

    private LeaseListAdapter adapter;

    private String provinceName = "";
    private String cityName = "";
    private String firstCategoryName;

    private String firstCategoryNo;
    private String secondCategoryNo = "";
    private String type;
    private int pageNum = 1;//当前页码
    public int pageSize = 10;//每页条数
    private String provinceNo = "";
    private String cityNo = "";
    private List<String> cityList = new ArrayList<>();
    private String isSelf;//是否自营,1为自营
    private String sortWay = "1";

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMachineComponent.builder().appComponent(appComponent)
                .machineModule(new MachineModule(this))
                .build()
                .inject(this);
    }

    public static void start(Context context, String categoryType, String firstCategoryNo, String firstCategoryName) {
        Intent intent = new Intent();
        intent.setClass(context, LeaseCategoryListActivity.class);
        intent.putExtra("categoryType", categoryType);
        intent.putExtra("firstCategoryNo", firstCategoryNo);
        intent.putExtra("firstCategoryName", firstCategoryName);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    private void initExtra() {
        if (getIntent() != null) {
            type = getIntent().getStringExtra("categoryType");
            firstCategoryNo = getIntent().getStringExtra("firstCategoryNo");
            firstCategoryName = getIntent().getStringExtra("firstCategoryName");
            if ("3".equals(type) || "6".equals(type)) {
                binding.rvConditionSelection.setVisibility(View.GONE);
//                binding.llTab.setVisibility(View.VISIBLE);
//                binding.selectLayout.setVisibility(View.GONE);
            } else {
                binding.rvConditionSelection.setVisibility(View.VISIBLE);
//                binding.llTab.setVisibility(View.GONE);
//                binding.selectLayout.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    protected void init() {
        initExtra();
        binding.topLayout.titleView.setText(firstCategoryName);
        provinceNo = viewModel.getAreaCodeModel();
        cityList = new ArrayList<>();
        viewModel.getFilterModelModel(type, firstCategoryNo);
        viewModel.getFilterSort();
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_lease_category_list);
        binding.topLayout.ivBack.setOnClickListener(this);
        binding.isSelfLayout.setOnClickListener(this);
        binding.areaLayout.setOnClickListener(this);
        binding.sortLayout.setOnClickListener(this);
        binding.ivMap.setOnClickListener(this);

        binding.tvIsSelf.setOnClickListener(this);
        binding.tvAddrArea.setOnClickListener(this);
        binding.tvSortWay.setOnClickListener(this);
        // 分类监听
        binding.rvConditionSelection.setTabMode(TabLayout.MODE_SCROLLABLE);
        binding.rvConditionSelection.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                checkDismiss(0);
                secondCategoryNo = CategoryList.get(tab.getPosition()).getId();
                loadData(false);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        if (adapter == null) {
            adapter = new LeaseListAdapter(getActivity(), null);
        }
        adapter.setOnItemClick(new AdapterOnItemClick<LeaseListEntity>() {
            @Override
            public void onItemClick(LeaseListEntity entity, int position) {
                if (!ClickUtils.isDoubleClick()) {
                    viewModel.getH5Url(entity.getType(), entity.getDataId());
                }
            }
        });
        binding.recyclerView.addItemDecoration(new RecyclerViewItemDecoration2(getResources().getDimension(R.dimen.dp10), getResources().getDimension(R.dimen.dp10)));
        binding.recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        binding.recyclerView.setFootViewText("加载中", "我也是有底线的");
        binding.recyclerView.setAdapter(adapter);

        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData(false);
            }

            @Override
            public void onLoadMore() {
                loadData(true);
            }
        });

        initFilterView();

    }

    private void initFilterView() {

        //排序选择
        sortWindow = new DictWindow5(getActivity());
        sortWindow.setFocusable(false);
        sortWindow.setOutsideTouchable(false);
        sortWindow.setOnCallBack(new DictWindow5.OnCallBack() {
            @Override
            public void result(DictEntity3 dictEntity) {
                updateChooseTextStatus(binding.sortLayout, binding.tvSort, 2, dictEntity.getName());
                sortWay = dictEntity.getId();
                loadData(false);
            }
        });
        sortWindow.setOnCloseBack(new DictWindow5.OnCloseBack() {
            @Override
            public void dismiss() {
                updateChooseTextStatus(binding.sortLayout, binding.tvSort, "排序".equals(binding.tvSort.getText()) ? 0 : 2, null);
            }
        });

        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setBgView(binding.grayLayout);
        mAddressPop.setMemberHeight();
        mAddressPop.setProvinceSingle();
        mAddressPop.setCitySingle();
        mAddressPop.setAreaMore();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnResultClick((key1, key2, key3) -> {
            try {
                List<BaseAreaEntity> listKey1 = (List<BaseAreaEntity>) key1;
                List<BaseAreaEntity> listKey2 = (List<BaseAreaEntity>) key2;
                List<BaseAreaEntity> listKey3 = (List<BaseAreaEntity>) key3;
                cityList = getCityList(listKey3);
                if (listKey2 != null && listKey2.size() > 0) {
                    cityName = listKey2.get(0).getName();
                    cityNo = listKey2.get(0).getNo();
                } else {
                    cityNo = "";
                }
                provinceName = listKey1.get(0).getName();
                provinceNo = listKey1.get(0).getNo();
                if (!TextUtils.isEmpty(cityName) && "不限".equals(cityName)) {
                    updateChooseTextStatus(binding.areaLayout, binding.tvArea, 2, cityName);
                } else {
                    updateChooseTextStatus(binding.areaLayout, binding.tvArea, 2, provinceName);
                }
            } catch (Exception exception) {
            }

            loadData(false);
        });
        mAddressPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                updateChooseTextStatus(binding.areaLayout, binding.tvArea, "地区".equals(binding.tvArea.getText()) ? 0 : 2, null);
            }
        });

    }


    private void loadData(boolean isLoadMore) {
        pageNum = isLoadMore ? pageNum + 1 : 1;
        if ("1".equals(type) || "2".equals(type)) {//接口入参字段不统一,兼容接口不同参数名称
            LeaseMachineFilterJson filterJson = new LeaseMachineFilterJson();
            filterJson.setType(type);
            filterJson.setFirstCategoryNo(firstCategoryNo);
            filterJson.setSecondCategoryNo(secondCategoryNo);
            filterJson.setIsSelf(isSelf);
            filterJson.setProvinceNo(provinceNo);
            filterJson.setCityNo(cityNo);
            filterJson.setAreaNoList(cityList);
            filterJson.setSortWay(sortWay);
            filterJson.setPageNum(pageNum);
            filterJson.setPageSize(pageSize);
            viewModel.getAllList(filterJson, isLoadMore);
        } else if ("3".equals(type)) {
            CarFilterJson filterJson = new CarFilterJson();
            filterJson.setType(type);
            filterJson.setModelId(firstCategoryNo);
            filterJson.setBrandId(secondCategoryNo);
            filterJson.setIsSelf(isSelf);
            filterJson.setProvinceNo(provinceNo);
            filterJson.setCityNo(cityNo);
            filterJson.setDistrictNo(cityList);
            filterJson.setSortWay(sortWay);
            filterJson.setPageNum(pageNum);
            filterJson.setPageSize(pageSize);
            viewModel.getAllList(filterJson, isLoadMore);
        } else if ("4".equals(type)) {
            HouseFilterJson filterJson = new HouseFilterJson();
            filterJson.setType(type);
            filterJson.setCategoryParentId(firstCategoryNo);
            filterJson.setCategoryChildId(secondCategoryNo);
            filterJson.setIsSelf(isSelf);
            filterJson.setProvinceNo(provinceNo);
            filterJson.setCityNo(cityNo);
            filterJson.setAreaNoList(cityList);
            filterJson.setSortWay(sortWay);
            filterJson.setPageNum(pageNum);
            filterJson.setPageSize(pageSize);
            viewModel.getAllList(filterJson, isLoadMore);
        } else if ("5".equals(type)) {
            LandFilterJson filterJson = new LandFilterJson();
            filterJson.setType(type);
            filterJson.setFirstCategoryNo(firstCategoryNo);
            filterJson.setSecondCategoryNo(secondCategoryNo);
            filterJson.setIsSelf(isSelf);
            filterJson.setProvinceNo(provinceNo);
            filterJson.setCityNo(cityNo);
            filterJson.setAreaNos(cityList);
            filterJson.setSortWay(sortWay);
            filterJson.setPageNum(pageNum);
            filterJson.setPageSize(pageSize);
            viewModel.getAllList(filterJson, isLoadMore);
        } else if ("6".equals(type)) {
            FactoryFilterJson filterJson = new FactoryFilterJson();
            filterJson.setType(type);
            filterJson.setFirstCategoryNo(firstCategoryNo);
            filterJson.setSecondCategoryNo(secondCategoryNo);
            filterJson.setIsSelf(isSelf);
            filterJson.setAreacode(provinceNo);
            filterJson.setCity(cityNo);
            filterJson.setArea(cityList);
            filterJson.setSortWay(sortWay);
            filterJson.setPageNum(pageNum);
            filterJson.setPageSize(pageSize);
            viewModel.getAllList(filterJson, isLoadMore);
        } else if ("7".equals(type)) {
            FarmFilterJson filterJson = new FarmFilterJson();
            filterJson.setType(type);
            filterJson.setFirstCategoryNo(firstCategoryNo);
            filterJson.setSecondCategoryNo(secondCategoryNo);
            filterJson.setIsSelf(isSelf);
            filterJson.setAreacode(provinceNo);
            filterJson.setCity(cityNo);
            filterJson.setArea(cityList);
            filterJson.setSortWay(sortWay);
            filterJson.setPageNum(pageNum);
            filterJson.setPageSize(pageSize);
            viewModel.getAllList(filterJson, isLoadMore);
        }
    }

    public void showList(List<LeaseListEntity> list, boolean isLoadMore) {
        binding.recyclerView.setNoMore(list.size() < pageSize);
        if (isLoadMore) {
            binding.recyclerView.loadMoreComplete();
            if (list.size() != 0) {
                adapter.addDatas(list);
            }
        } else {
            if (list.size() == 0) {
                binding.emptyView.setVisibility(View.VISIBLE);
            } else {
                binding.emptyView.setVisibility(View.GONE);
            }

            binding.recyclerView.refreshComplete();
            adapter.setDatas(list);
        }
    }

    //设置二级分类数据
    public void showBrandPopWindow(List<DictEntity3> data) {
        this.CategoryList = data;
        if (data == null || data.size() == 0) {
            return;
        }

        if ("不限".equals(data.get(0).getName().trim())) {
            CategoryList.get(0).setName("全部");
        }

        for (int i = 0; i < CategoryList.size(); i++) {
            binding.rvConditionSelection.addTab(binding.rvConditionSelection.newTab().setText(CategoryList.get(i).getName()));
        }
        binding.rvConditionSelection.getTabAt(0).select();
    }


    //设置排序数据
    public void showSortPopWindow(List<DictEntity3> data) {
        this.sortDictEntityList = data;
        if (data == null || data.size() == 0) {
            return;
        }

        sortWay = data.get(0).getId();
        sortWindow.setData(data);
        sortWindow.setCheckDefaultById(sortWay);
    }


    public void showAddressDatas(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data, String provinceNo) {
        this.areaEntityList = data;
        if (data != null && data.size() > 0) {
            this.provinceNo = provinceNo;
            mAddressPop.setData(data, true, provinceNo);
        }
    }

    private List<String> getCityList(List<BaseAreaEntity> list) {
        cityList = new ArrayList<>();
        for (BaseAreaEntity entity : list) {
            if (!TextUtils.isEmpty(entity.getNo())) {
                cityList.add(entity.getNo());
            }
        }
        return cityList;
    }

    @Override
    public void onClick(View v) {
        checkDismiss(v.getId());
        switch (v.getId()) {
            case R.id.isSelf_layout://是否自营
                if (TextUtils.isEmpty(isSelf)) {
                    isSelf = "1";
                    binding.isSelfLayout.setBackgroundResource(R.drawable.search_new_blue_bg);
                    binding.tvSelf.setTextColor(getResources().getColor(R.color.red));
                } else {
                    isSelf = "";
                    binding.isSelfLayout.setBackgroundResource(R.drawable.search_bg);
                    binding.tvSelf.setTextColor(getResources().getColor(R.color.color_333333));
                }
                loadData(false);
                break;
            case R.id.area_layout://地区
                updateChooseTextStatus(binding.areaLayout, binding.tvArea, "地区".equals(binding.tvArea.getText()) ? -1 : 1, null);
                mAddressPop.showPopwindow(binding.areaLayout);
                if (areaEntityList == null) {
                    viewModel.getCityData();
                }
                break;
            case R.id.sort_layout://排序
                updateChooseTextStatus(binding.sortLayout, binding.tvSort, "排序".equals(binding.tvSort.getText()) ? -1 : 1, null);
                sortWindow.setCheckDefaultById(sortWay);
                sortWindow.showPopwindow(binding.sortLayout);
                if (sortDictEntityList == null) {
                    viewModel.getFilterSort();
                }
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_isSelf://是否自营
                if (TextUtils.isEmpty(isSelf)) {
                    isSelf = "1";
                    binding.tvIsSelf.setTextColor(getResources().getColor(R.color.red));
                } else {
                    isSelf = "";
                    binding.tvIsSelf.setTextColor(getResources().getColor(R.color.color_333333));
                }
                loadData(false);
                break;
            case R.id.tv_addr_area:
                updateChooseTextStatus2(binding.tvAddrArea, "地区".equals(binding.tvAddrArea.getText()) ? -1 : 1, null);
                mAddressPop.showPopWindowDropDown(binding.tvAddrArea, getResources().getDimensionPixelOffset(R.dimen.dp1));
                if (areaEntityList == null) {
                    viewModel.getCityData();
                }
                break;
            case R.id.tv_sort_way://排序
                updateChooseTextStatus2(binding.tvSortWay, "排序".equals(binding.tvSort.getText()) ? -1 : 1, null);
                sortWindow.setCheckDefaultById(sortWay);
                sortWindow.showPopWindowDropDown(binding.tvSortWay, getResources().getDimensionPixelOffset(R.dimen.dp1));
                if (sortDictEntityList == null) {
                    viewModel.getFilterSort();
                }
                break;
            case R.id.iv_map://打开地图定位
                startMap();
                break;
        }
    }

    private void checkDismiss(int resId) {
        if (mAddressPop != null && mAddressPop.isShowing() && R.id.area_layout != resId) {
            mAddressPop.dismiss();
        }
        if (sortWindow != null && sortWindow.isShowing() && R.id.sort_layout != resId) {
            sortWindow.dismiss();
        }
    }

    //更新选项颜色
    private void updateChooseTextStatus(View view, TextView textView, int value, String name) {
        if (value == 0) {
            setTextViewBg(view, textView, R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333);
        } else if (value == -1) {
            setTextViewBg(view, textView, R.drawable.search_bg, R.mipmap.ic_up_arrow_n, R.color.color_333333);
        } else if (value == 1) {
            setTextViewBg(view, textView, R.drawable.search_new_blue_bg, R.mipmap.icon_up_red, R.color.color_main);
        } else if (value == 2) {
            setTextViewBg(view, textView, R.drawable.search_new_blue_bg, R.mipmap.icon_down_red, R.color.color_main);
        }
        if (TextUtils.isEmpty(name)) return;
        textView.setText(name);
    }

    //设置背景色和图标
    private void setTextViewBg(View view, TextView textView, int bg, int img, int textColor) {
        view.setBackgroundResource(bg);
        Drawable drawable_n = getResources().getDrawable(img);
        drawable_n.setBounds(0, 0, drawable_n.getMinimumWidth(), drawable_n.getMinimumHeight());
        textView.setCompoundDrawables(null, null, drawable_n, null);
        textView.setTextColor(getResources().getColor(textColor));
    }

    //更新选项颜色2
    private void updateChooseTextStatus2(TextView textView, int value, String name) {
        if (!TextUtils.isEmpty(name)) {
            textView.setText(name);
        }
        if (value == 0) {
            setTextViewBg2(textView, R.mipmap.ic_down_arrow_n, R.color.color_333333);
        } else if (value == -1) {
            setTextViewBg2(textView, R.mipmap.ic_up_arrow_n, R.color.color_333333);
        } else if (value == 1) {
            setTextViewBg2(textView, R.mipmap.icon_up_red, R.color.color_main);
        } else if (value == 2) {
            setTextViewBg2(textView, R.mipmap.icon_down_red, R.color.color_main);
        }
    }

    //设置背景色和图标2
    private void setTextViewBg2(TextView textView, int img, int textColor) {
        Drawable drawable_n = getResources().getDrawable(img);
        drawable_n.setBounds(0, 0, drawable_n.getMinimumWidth(), drawable_n.getMinimumHeight());
        textView.setCompoundDrawables(null, null, drawable_n, null);
        textView.setTextColor(getResources().getColor(textColor));
    }

    public void startMap() {
        Intent intent = new Intent();
        intent.setClass(this, SelectAddressActivity.class);
        intent.putExtra(SelectAddressActivity.TITLE, "详细地址");
        intent.putExtra(SelectAddressActivity.HINT, "请输入地址");
        intent.putExtra(SelectAddressActivity.SAVE_TEXT, "确定");
        if(!TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData("distance_latitude",""))){
            intent.putExtra(SelectAddressActivity.LATITUDE, Double.parseDouble(SharedPreferenceUtil.getInstance().getSaveStringData("distance_latitude","")));
            intent.putExtra(SelectAddressActivity.LONGTITUDE, Double.parseDouble(SharedPreferenceUtil.getInstance().getSaveStringData("distance_longitude","")));
        }
        startActivityForResult(intent, 255);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 255 && data != null) {
                double lat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
                double lon = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
                String address = data.getStringExtra(SelectAddressActivity.CURRENT_POSITION);
                //保存定位数据,用来给后端传参计算距离
                SharedPreferenceUtil.getInstance().saveData("distance_latitude", String.valueOf(lat));
                SharedPreferenceUtil.getInstance().saveData("distance_longitude", String.valueOf(lon));
                loadData(false);
            }
        }
    }
}
